#!/bin/bash

runtime=120
dev=""
directory=""

function realdev
{
	link=`readlink $dev`
	if [ "$link" == "" ]; then
		echo $dev
	else
		echo -e $dev | awk -F "/" '
		{
			for (i=1;i<NF;++i) {
				if (i!=1) {
					printf("/");
				}
				printf("%s", $i);
			}
		}'
		echo "/"$link
	fi
}

function devname
{
	realdev | awk -F "/" '{print $NF}'
}

function _start_iostat
{
	tmp=/tmp/iostat.$$$$.res
	iostat -xmd `devname` | grep -v `devname` > $tmp
	iostat -xmd 3 `devname` | grep --line-buffered -A 0 `devname` >> $tmp &
}

function _end_iostat
{
	tmp=/tmp/iostat.$$$$.res
	ps -ef | grep iostat | grep -v grep | grep $$ | awk '{print $2}' | xargs kill > /dev/null 2> /dev/null
	cat $tmp
	rm -rf $tmp
}

function libaio
{
	real=`realdev`
	op=$1
	bs=$2
	iodepth=$3
	_start_iostat
	fio \
		--name=fio_test --direct=1 --group_reporting \
		--ioengine=libaio:userspace_reap \
		--iodepth=$iodepth \
		--iodepth_batch_complete=0 \
		--size=`blockdev --getsize64 $real` \
		--filename=$real \
		--numjobs=1 \
		--runtime=$runtime \
		--bs=$bs \
		--rw=$op \
		$4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} ${14} ${15} ${16} ${17} ${18} ${19} ${20}
	sleep 10
	_end_iostat
}

function psync
{
	real=`realdev`
	op=$1
	bs=$2
	numjobs=$3
	_start_iostat
	fio \
		--name=fio_test --direct=1 --group_reporting \
		--ioengine=psync \
		--size=`blockdev --getsize64 $real` \
		--filename=$real \
		--numjobs=$numjobs \
		--runtime=$runtime \
		--bs=$bs \
		--rw=$op \
		$4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} ${14} ${15} ${16} ${17} ${18} ${19} ${20}
	sleep 10
	_end_iostat
}

function test
{
	name=`echo $@ | awk '
	{
		for (i=1;i<=NF;++i) {
			if (i!=1) {
				printf("_");
			}
			printf("%s", $i);
		}
	}'`
	if [ "$directory" == "" ]; then
		path=$name
	else
		path=$directory/$name
	fi
	$@ > $path
}
